import {marked} from "https://lib.baomitu.com/marked/14.1.1/lib/marked.esm.js";
import * as blog from "./api/blog.js";
import * as user from "./api/user.js";

const config = {
    doms: {
        asideAvatar: {
            asideProfileImg: document.querySelector(".aside-profile img"),
            asideProfileTitle: document.querySelector(".aside-profile .aside-profile-title"),
            asideProfileDescript: document.querySelector(".aside-profile .aside-profile-description"),
        },
        asideButtons: document.querySelector(".aside-buttons"),
    }
}

await init();
rgEvent();

function rgEvent() {
    const config = {
        doms: {
            asideAvatar: {
                asideProfileImg: document.querySelector(".aside-profile img"),
                asideProfileTitle: document.querySelector(".aside-profile .aside-profile-title"),
                asideProfileDescript: document.querySelector(".aside-profile .aside-profile-description"),
                iconTuichudenglu: document.querySelector(".icon-tuichudenglu"),
                iconShanchu: document.querySelector(".icon-shanchu"),
            },
            asideButtons: document.querySelector(".aside-buttons"),
            mainContainer: {
                markdowmBox: document.getElementById("markdowmBox"),
                bianji: document.querySelector(".icon-bianji"),
                tijiao: document.querySelector(".icon-tijiao"),
                mdEdit: document.getElementById("mdEdit"),
                baocun: document.querySelector(".icon-baocun"),
            },
            tips: document.getElementById("tips"),
            defaultAdd: {
                tianjiawenjian: document.querySelector(".defaultAdd .icon-tianjiawenjian"),
            }
        },
        curClassify: "null", // 当前被点击的分类名称
        curTitle: "null", // 当前选中文章的名称
        curContent: "null", // 当前展示的文章内容
        curEdit: null, // 编辑器的实例
    }

    rgClassify();
    rgArticleClick();
    rgEditArticle();
    rgSave();
    rgEditAndSave();
    rgAddBlog();
    rgMobSidbar();
    rgIconTuichudenglu();
    rgDelBlog();

    function rgDelBlog() {
        $(config.doms.asideAvatar.iconShanchu)
            .click(async function(e) {
                console.log('aaa')
                const resp = await blog.delBlog($(this).prev().val());
                console.log(resp);
                // 更新相应分类的目录
                await initBlogCatalog();
                // 注册相应的事件
                rgClassify();
                rgArticleClick();
            })
    }

    // 退出登陆
    function rgIconTuichudenglu() {
        $(config.doms.asideAvatar.iconTuichudenglu)
            .click(function(e) {
                location.href = "./login.html";
            })
    }

    /**
     * 加工中.........
     */
    function rgMobSidbar() {
        
    }

    // 注册添加博客事件
    function rgAddBlog() {
        $(config.doms.defaultAdd.tianjiawenjian)
            .click(function () {
                myPlugin.uploadForm({
                    article: {
                        classify: config.curClassify,
                    },
                    callback: async function (data) {
                        const resp = await blog.upload(data);
                        showTips(resp.msg);
                        closeBlog();
                        openBlog(data.content);
                        config.curTitle = data.title;
                        config.curClassify = data.classify;
                        config.curContent = data.content;
                        // 更新相应分类的目录
                        await initBlogCatalog();
                        // 注册相应的事件
                        rgClassify();
                        rgArticleClick();
                    }
                })
            })
    }

    // 文章上传 保存 并展示 
    function rgEditAndSave() {
        $(config.doms.mainContainer.tijiao)
            .click(async function () {
                // 1.拿到更新后的文章内容
                var content = $('.editormd-markdown-textarea').val();
                config.curContent = content;
                // 2.上传新的文章给服务器
                const respon = await blog.upload({
                    "classify": config.curClassify,
                    "title": config.curTitle,
                    "content": config.curContent
                });
                // 3.收起编辑器
                closeEdit();
                // 4.展示当前编辑的这篇博客
                closeBlog();
                openBlog(config.curContent);
            })
    }

    // 文章修改保存
    function rgSave() {
        $(config.doms.mainContainer.baocun)
            .click(async function () {
                // 1.拿到更新后的文章内容
                var content = $('.editormd-markdown-textarea').val();
                config.curContent = content;
                // 2.上传新的文章给服务器
                const respon = await blog.upload({
                    "classify": config.curClassify,
                    "title": config.curTitle,
                    "content": config.curContent
                });
                // 3.展示上传成功的提示
                showTips(respon.msg);
            })
    }

    // 展示提示
    function showTips(msg) {
        config.doms.tips.querySelector("span").innerText = msg;
        config.doms.tips.style.display = "block";
        let timer = setTimeout(function () {
            config.doms.tips.querySelector("span").innerText = "";
            config.doms.tips.style.display = "none";
            timer = null;
        }, 1000);
    }

    // 注册编辑按纽
    function rgEditArticle() {
        $(config.doms.mainContainer.bianji)
            .click(function () {
                // 收起博客
                closeBlog();
                // 拉起编辑器
                openEdit(config.curContent);
            })
    }

    // 收起编辑器
    function closeEdit() {
        config.curEdit = null;
        config.doms.mainContainer.mdEdit.style.display = "none";
    }

    // 拉起编辑器
    function openEdit(mdContent) {
        // 注册Editor.md实例
        config.curEdit = editormd("editormd", {
            width: "90%",
            height: "100%",
            syncScrolling: "single",
            markdown: mdContent,     // dynamic set Markdown text
            path: "./assce/editor_md/lib/",
        });
        config.doms.mainContainer.mdEdit.style.display = "block";
    }

    // 注册文章点击事件
    function rgArticleClick() {
        $(config.doms.asideButtons)
            .find("li .fileDirectory")
            .click(async function (e) {
                if(e.target.nodeName === "I") {
                    // 删除博客
                    const resp = await blog.delBlog($(e.target).prev().text());
                    if(resp.code === 200) {
                        // 更新相应分类的目录
                        await initBlogCatalog();
                        // 注册相应的事件
                        rgClassify();
                        rgArticleClick();
                    }else {
                        alert(resp.data);
                    }
                    return ;
                }
                // 1.获取文章标题
                const title = e.target.innerText;
                // 2.从服务器中获取文章信息
                const articleMsg = await blog.getArticle(title).then(resp => resp.data);
                // 3.展开博客
                if (config.curEdit) {
                    // 如果打开了编辑器，收起
                    closeEdit();
                }
                closeBlog(); // 收起上一篇博客
                openBlog(articleMsg.content);
                config.curTitle = title;
                config.curContent = articleMsg.content;
            })
    }

    // 收起博客
    function closeBlog() {
        const markdownBody = config.doms.mainContainer.markdowmBox.querySelector(".markdown-body");
        markdownBody.innerHTML = "";
        config.doms.mainContainer.markdowmBox.style.display = "none";
    }

    // 展开博客
    function openBlog(mdContent) {
        const markdownBody = config.doms.mainContainer.markdowmBox.querySelector(".markdown-body");
        const mdDiv = analysisBlog(mdContent);
        markdownBody.appendChild(mdDiv);
        config.doms.mainContainer.markdowmBox.style.display = "block";
    }

    // 将博客内容解析成html
    function analysisBlog(mdData) {
        const mdHTML = marked.parse(mdData);
        const div = document.createElement("div");
        div.innerHTML = mdHTML;
        // 代码高亮
        const codes = div.querySelectorAll("pre code");
        Array.from(codes).forEach(code => {
            let language = code.className.replace(/language-(?=.*)/g, "");
            if (!language) {
                language = "shell";
            }
            const highlightedCode = hljs.highlight(code.innerText, { language }).value;
            code.innerHTML = highlightedCode;
        })
        return div;
    }

    // 注册分类目录下拉事件
    function rgClassify() {
        $(config.doms.asideButtons)
            .find('li .router-link-active')
            .click(function () {
                const li = this.parentElement;
                // 1.关闭已经展开目录
                // 1.1 得到已经展开的目录
                const active = config.doms.asideButtons.querySelector(`li.on`);
                // 1.2 关闭已经展开的目录
                if (active && active !== li) {
                    closeMenu(active);
                }
                // 2.处理被点击的目录
                li.className === "on" ? closeMenu(li) : openMenu(li);
                config.curClassify = this.querySelector('span').innerText;
            })
    }

    // 关闭目录
    function closeMenu(dom) {
        dom.style.height = "45px";
        const arrow = dom.querySelector("i");
        arrow.style.transform = "rotate(0deg)";
        dom.className = "off";
    }

    // 开启目录
    function openMenu(dom) {
        const height = calcMenuHeight(dom);
        dom.style.height = height + "px";
        const arrow = dom.querySelector("i");
        arrow.style.transform = "rotate(90deg)";
        dom.className = "on";
    }

    // 计算目录新高度
    function calcMenuHeight(dom) {
        const cnt = dom.querySelectorAll(".fileDirectory li").length;
        return cnt * 30 + 45;
    }
}

// 初始化页面信息
async function init() {
    const config = {
        doms: {
            asideAvatar: {
                asideProfileImg: document.querySelector(".aside-profile img"),
                asideProfileTitle: document.querySelector(".aside-profile .aside-profile-title"),
                asideProfileDescript: document.querySelector(".aside-profile .aside-profile-description"),
            },
            asideButtons: document.querySelector(".aside-buttons"),
        }
    }

    initUserInfo();
    await initBlogCatalog();

    // 初始化侧边栏头部信息
    async function initUserInfo() {
        const userInfo = await user.getUser().then(resp => resp.data);
        setAsideProfile(userInfo);
    }

    /**
     * 设置侧边栏头部信息
     * @param {object} info // 用户信息
     */
    function setAsideProfile(info) {
        const doms = config.doms.asideAvatar;
        doms.asideProfileImg.src = info.userImg;
        doms.asideProfileTitle.innerText = info.userNickname;
    }
}

// 初始化分类目录下的文章标题
function initTitle() {
    // 1.获取所有分类标签元素
    const lis = config.doms.asideButtons.querySelectorAll('li');
    // 2.添加分类所有的文章标题
    lis.forEach(async li => {
        // 添加文章标题
        // 1.获取分类名称
        const span = li.querySelector(".router-link-active span");
        const fileDirectory = li.querySelector(".fileDirectory");
        const classify = span.innerText;
        // 2.用分类名称从服务器中拿到所有的文章标题
        const titles = await blog.getTitle(classify).then(resp => resp.data);
        // 3.将文章标题全部加入
        titles.forEach(title => {
            const titleLi = document.createElement("li");
            const span = document.createElement("span");
            span.innerText = title;
            titleLi.appendChild(span);
            const i = document.createElement("i");
            i.className = "iconfont icon-shanchu";
            titleLi.appendChild(i);
            fileDirectory.appendChild(titleLi);
        })
    })
}

// 初始化博客目录
async function initBlogCatalog() {
    // 1.初始化分类标签
    await initClassify();
    // 2.根据分类初始化文件标题
    initTitle();
}

// 初始化分类标签
async function initClassify() {
    // 1.获取所有的分类
    const classifications = await blog.getClassifications().then(resp => resp.data);

    // 2.将分类元素加入到目录
    addClassificationsMenu(classifications);
}

// 添加分类标签
function addClassificationsMenu(classifyInfo) {
    let dom = config.doms.asideButtons;
    dom.innerHTML = '';
    classifyInfo.forEach(classify => {
        const classifyEle = document.createElement("li");
        classifyEle.className = "off";
        classifyEle.innerHTML = `
            <div class="router-link-active">
                <i class="iconfont icon-youjiantou"></i>
                <span>${classify}</span>
            </div>
            <ul class="fileDirectory"></ul>
        `;
        dom.appendChild(classifyEle);
    })
}